<?php
/**
 * Created by PhpStorm.
 * User: 14775
 * Date: 2017/5/31
 * Time: 13:56
 */

namespace Sqapi\BLL;


use Common\Lib\RedisHandle;

class Authenticate
{
    /**
     * 获取accessToken
     * @param $appid
     * @param $appsecret
     * @param $ip
     * @return bool
     */
    public function getAccessToken($appid, $appsecret, $ip)
    {
        $curTime = time();

        $accessToken = RedisHandle::getAccessTokenByAppid($appid);
        if ($accessToken) {
            $appinfo = RedisHandle::getAppinfoByAccessToken($accessToken);
            if ($appinfo && $curTime - $appinfo['time'] <= 10 && $appinfo['appsecret'] == $appsecret && $appinfo['ip'] == $ip) {
                return array('success' => true, 'code' => 200, 'data' => $accessToken);
            }
        }

        $app = M('sys_applicaion')->where(array('appid' => $appid, 'appsecret' => $appsecret))->find();
        if (!$app) {
            return array('success' => false, 'code' => 700); //应用不存在
        }
        if (!$app['use_flg']) {
            return array('success' => false, 'code' => 701);//应用已禁用
        }

        if (!in_array($ip, explode(',', $app['ip_list']))) {
            return array('success' => false, 'code' => 702);//IP验证失败
        }

        //IP白名单验证
        $accessToken = md5($appid . $appsecret . $ip . $curTime);

        $app['time'] = $curTime;
        $app['ip'] = $ip;
        RedisHandle::saveAccessToken($accessToken, $appid, $app);
        return array('success' => true, 'code' => 200, 'data' => $accessToken);
    }

    /**
     * 验证Token
     * @param $accessToken
     * @param $ip
     * @return bool
     */
    public function validate($accessToken, $ip)
    {
        $appinfo = $this->getAppinfo($accessToken);
        if (!$appinfo) {
            return false;//接口未授权
        }
        if (!in_array($ip, explode(',', $appinfo['ip_list']))) {
            return false;//IP验证失败
        }
        return true;
    }

    /**
     *
     * @param $accessToken
     * @return mixed
     */
    public function getAppinfo($accessToken)
    {
        return RedisHandle::getAppinfoByAccessToken($accessToken);
    }

}